/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package v.main;

import com.sun.jndi.toolkit.url.UrlUtil;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.ICallBack;
import m.lang.LangModels;
import m.sus.SUSModels;
import util.JComboboxForHashMapItem;
import util.LoggerUtil;
import util.URLUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *
 * @author SoChishun
 */
public class FrmMain extends javax.swing.JFrame {

    Locale locale = Locale.getDefault(); // 当前语言
    Properties appconf = new Properties(); // 应用配置内容
    boolean documentStatus = false; // 文档状态
    final Logger logger=Logger.getLogger(FrmMain.class.getName());

    /**
     * Creates new form FrmMain
     */
    public FrmMain() {
        initComponents();
        // 初始化日志
        try {
            LoggerUtil.initLogger();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, ex.getMessage());
        }
        logger.info("启动成功!");

        this.setLocationRelativeTo(null); // 窗体居中对齐 2016-5-17
        // 控件设置
        lbl_title.setFont(new Font("微软雅黑", Font.BOLD, 12));
        txtpanel_main.setContentType("text/html");

        this.loadAppConf(); // 加载应用配置

        // 2016-5-27
        loadLangCombobox();

        loadFrame();
    }

    /**
     * 加载语言下拉框
     *
     * @since 1.0 2016-5-27 SoChishun Added.
     */
    void loadLangCombobox() {
        JComboboxForHashMapItem cbbHashMap = new JComboboxForHashMapItem();
        cbbHashMap.setCombobox(cbb_lang, LangModels.getLangs());
        // 切换语言界面
        cbb_lang.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                HashMap item = (HashMap) cbb_lang.getSelectedItem();
                locale = new Locale(item.get("id").toString());
                loadLangUI();
            }
        });
    }

    /**
     * 加载应用配置信息
     *
     * @since 1.0 2016-6-9 SoChishun Added.
     */
    void loadAppConf() {
        try {
            appconf.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("res/jcliveupdate.properties"));
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 加载指定语言的界面
     *
     * @since 1.0 2016-5-27
     */
    void loadLangUI() {
        LangModels.setLocale(locale);
        this.setTitle(LangModels.getString("app-title") + " " + appconf.getProperty("version"));
        // 按钮
        btn_remind.setText(LangModels.getString("button-remind-text"));
        btn_run.setText(LangModels.getString("button-run-text"));
        btn_skip.setText(LangModels.getString("button-skip-text"));
        // 标签
        if (documentStatus) {
            loadUpdateMessage();
        } else {
            lbl_title.setText(LangModels.getString("label-title-text"));
            txtpanel_main.setText("<div style=\"color:#333;\"><div>" + LangModels.getString("panel-main-text") + "</div></div>");
        }
        // txtpanel_main.setText("<div style=\"color:#333;\"><h1 style=\"background-color:#eff4fb\">Version:1.0.0.0</h1><div>dfsdf</div></div>");
    }

    /**
     * 加载升级文件信息
     *
     * @since 1.0 2016-6-9 SoChishun Added.
     */
    void loadUpdateMessage() {
        // 加载远程资源成功
        if (SUSModels.isNewVersion(appconf.getProperty("version"))) {
            lbl_title.setText(LangModels.getString("label-title-yes-text"));
            txtpanel_main.setText(SUSModels.getVersionMessage(locale.toString()));
        } else {
            lbl_title.setText(LangModels.getString("label-title-no-text"));
            txtpanel_main.setText(SUSModels.getVersionMessage(locale.toString()));
        }

    }

    /**
     * 按钮点击事件
     *
     * @since 1.0 2016-6-9 SoChishun Added.
     */
    void setButtonAction() {
        // 忽略按钮(直接关闭)
        btn_skip.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        // 下次提醒
        btn_remind.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        // 立即更新
        btn_run.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SUSModels.doUpdate();
            }
        });
    }

    /**
     * 加载窗体
     *
     * @since 1.0 2016-5-26 SoChishun Added.
     */
    void loadFrame() {
        loadLangUI();
        setButtonAction(); // 2016-6-9 按钮点击事件处理
        SUSModels.doRead(
                new ICallBack() {
            @Override
            public void execute() {
                loadUpdateMessage();
                documentStatus = true;
            }
        },
                new ICallBack() {
            @Override
            public void execute() {
                // 加载远程资源失败
                lbl_title.setText(LangModels.getString("label-title-fail-text"));
                txtpanel_main.setText(LangModels.getString("panel-main-fail-text"));
                documentStatus = false;
            }
        }
        );
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbl_title = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtpanel_main = new javax.swing.JTextPane();
        btn_skip = new javax.swing.JButton();
        btn_remind = new javax.swing.JButton();
        btn_run = new javax.swing.JButton();
        cbb_lang = new javax.swing.JComboBox<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lbl_title.setText("发现新版本!");

        txtpanel_main.setContentType("text/html"); // NOI18N
        jScrollPane2.setViewportView(txtpanel_main);

        btn_skip.setText("忽略");

        btn_remind.setText("下次提醒我");

        btn_run.setText("立即升级");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btn_skip)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_remind)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_run))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lbl_title)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cbb_lang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_title)
                    .addComponent(cbb_lang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_skip)
                    .addComponent(btn_remind)
                    .addComponent(btn_run))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmMain().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_remind;
    private javax.swing.JButton btn_run;
    private javax.swing.JButton btn_skip;
    private javax.swing.JComboBox<HashMap> cbb_lang;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbl_title;
    private javax.swing.JTextPane txtpanel_main;
    // End of variables declaration//GEN-END:variables
}
